// 打卡拍照页面交互功能

document.addEventListener('DOMContentLoaded', function() {
    // 初始化相机功能
    initializeCamera();
    
    // 设置拍照模式
    setupPhotoModes();
    
    // 设置拍照控制
    setupCameraControls();
    
    // 设置滤镜功能
    setupFilters();
    
    // 设置底部导航
    setupBottomNavigation();
    
    // 设置位置服务
    setupLocationService();
});

// 初始化相机
function initializeCamera() {
    // 模拟相机初始化
    const cameraPreview = document.querySelector('.camera-preview');
    const focusFrame = document.querySelector('.focus-frame');
    
    // 添加对焦动画
    setTimeout(() => {
        focusFrame.classList.add('active');
        setTimeout(() => {
            focusFrame.classList.remove('active');
        }, 1000);
    }, 1500);
    
    // 模拟自动对焦
    setInterval(() => {
        if (Math.random() > 0.7) {
            focusFrame.classList.add('active');
            setTimeout(() => {
                focusFrame.classList.remove('active');
            }, 800);
        }
    }, 3000);
    
    // 请求相机权限
    requestCameraPermission();
}

// 请求相机权限
function requestCameraPermission() {
    // 这里可以添加实际的相机权限请求逻辑
    console.log('请求相机权限...');
    
    // 模拟权限请求结果
    setTimeout(() => {
        console.log('相机权限已获取');
        showToast('相机已就绪');
    }, 1000);
}

// 设置拍照模式
function setupPhotoModes() {
    const modeBtns = document.querySelectorAll('.mode-btn');
    
    modeBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除所有活动状态
            modeBtns.forEach(b => b.classList.remove('active'));
            
            // 设置当前模式为活动状态
            this.classList.add('active');
            
            // 切换拍照模式
            const mode = this.dataset.mode;
            switchPhotoMode(mode);
            
            // 添加点击动画
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = 'scale(1)';
            }, 150);
        });
    });
}

// 切换拍照模式
function switchPhotoMode(mode) {
    const cameraPreview = document.querySelector('.camera-preview');
    
    switch(mode) {
        case 'normal':
            cameraPreview.style.filter = 'none';
            showToast('普通模式');
            break;
        case 'portrait':
            cameraPreview.style.filter = 'blur(1px)';
            showToast('人像模式');
            break;
        case 'landscape':
            cameraPreview.style.filter = 'contrast(1.2) saturate(1.3)';
            showToast('风景模式');
            break;
        case 'ar':
            cameraPreview.style.filter = 'hue-rotate(30deg)';
            showToast('AR模式');
            break;
    }
}

// 设置相机控制
function setupCameraControls() {
    const flashBtn = document.getElementById('flashBtn');
    const timerBtn = document.getElementById('timerBtn');
    const switchCameraBtn = document.getElementById('switchCameraBtn');
    const captureBtn = document.getElementById('captureBtn');
    const galleryBtn = document.getElementById('galleryBtn');
    const filterBtn = document.getElementById('filterBtn');
    
    // 闪光灯按钮
    flashBtn.addEventListener('click', function() {
        toggleFlash();
    });
    
    // 定时器按钮
    timerBtn.addEventListener('click', function() {
        toggleTimer();
    });
    
    // 切换相机按钮
    switchCameraBtn.addEventListener('click', function() {
        switchCamera();
    });
    
    // 拍照按钮
    captureBtn.addEventListener('click', function() {
        takePhoto();
    });
    
    // 相册按钮
    galleryBtn.addEventListener('click', function() {
        openGallery();
    });
    
    // 滤镜按钮
    filterBtn.addEventListener('click', function() {
        openFilterModal();
    });
}

// 切换闪光灯
function toggleFlash() {
    const flashBtn = document.getElementById('flashBtn');
    const isActive = flashBtn.classList.contains('active');
    
    if (isActive) {
        flashBtn.classList.remove('active');
        showToast('闪光灯已关闭');
    } else {
        flashBtn.classList.add('active');
        showToast('闪光灯已开启');
        // 模拟闪光灯效果
        createFlashEffect();
    }
}

// 创建闪光灯效果
function createFlashEffect() {
    const flash = document.createElement('div');
    flash.style.position = 'fixed';
    flash.style.top = '0';
    flash.style.left = '0';
    flash.style.width = '100%';
    flash.style.height = '100%';
    flash.style.background = 'white';
    flash.style.zIndex = '999';
    flash.style.animation = 'flash 0.2s ease-out forwards';
    
    document.body.appendChild(flash);
    
    setTimeout(() => {
        flash.remove();
    }, 200);
}

// 切换定时器
function toggleTimer() {
    const timerBtn = document.getElementById('timerBtn');
    const isActive = timerBtn.classList.contains('active');
    
    if (isActive) {
        timerBtn.classList.remove('active');
        showToast('定时器已关闭');
    } else {
        timerBtn.classList.add('active');
        showToast('定时器已开启 (3秒)');
        startTimerCountdown();
    }
}

// 开始倒计时
function startTimerCountdown() {
    let countdown = 3;
    const timerBtn = document.getElementById('timerBtn');
    
    const countdownInterval = setInterval(() => {
        if (countdown > 0) {
            timerBtn.innerHTML = `<i class="fas fa-${countdown}"></i>`;
            countdown--;
        } else {
            clearInterval(countdownInterval);
            timerBtn.innerHTML = '<i class="fas fa-clock"></i>';
            timerBtn.classList.remove('active');
            // 自动拍照
            takePhoto();
        }
    }, 1000);
}

// 切换相机
function switchCamera() {
    const switchCameraBtn = document.getElementById('switchCameraBtn');
    
    // 添加切换动画
    switchCameraBtn.style.transform = 'rotate(180deg)';
    setTimeout(() => {
        switchCameraBtn.style.transform = 'rotate(0deg)';
    }, 300);
    
    showToast('切换摄像头');
    console.log('切换前后摄像头');
}

// 拍照功能
function takePhoto() {
    const captureBtn = document.getElementById('captureBtn');
    const captureInner = captureBtn.querySelector('.capture-inner');
    
    // 拍照动画
    captureInner.style.background = '#dcfce7';
    captureInner.style.transform = 'scale(0.8)';
    
    setTimeout(() => {
        captureInner.style.background = 'white';
        captureInner.style.transform = 'scale(1)';
    }, 200);
    
    // 创建快门效果
    createShutterEffect();
    
    // 模拟拍照过程
    console.log('拍照中...');
    
    // 显示成功消息
    setTimeout(() => {
        showSuccessToast('打卡成功！');
        updateCheckinCount();
        
        // 模拟保存照片到相册
        savePhotoToGallery();
    }, 500);
}

// 创建快门效果
function createShutterEffect() {
    const shutter = document.createElement('div');
    shutter.style.position = 'fixed';
    shutter.style.top = '0';
    shutter.style.left = '0';
    shutter.style.width = '100%';
    shutter.style.height = '100%';
    shutter.style.background = 'white';
    shutter.style.zIndex = '999';
    shutter.style.animation = 'shutter 0.3s ease-out forwards';
    
    document.body.appendChild(shutter);
    
    setTimeout(() => {
        shutter.remove();
    }, 300);
}

// 更新打卡次数
function updateCheckinCount() {
    const checkinCount = document.querySelector('.fa-clock').parentElement.nextElementSibling.querySelector('span');
    const currentCount = parseInt(checkinCount.textContent);
    checkinCount.textContent = currentCount + 1;
}

// 保存照片到相册
function savePhotoToGallery() {
    // 模拟保存照片
    console.log('照片已保存到相册');
    
    // 更新相册预览
    const galleryBtn = document.getElementById('galleryBtn');
    const img = galleryBtn.querySelector('img');
    
    // 随机选择一张新照片
    const newPhotoUrl = `https://images.unsplash.com/photo-${Date.now()}?w=60&h=60&fit=crop`;
    img.src = newPhotoUrl;
}

// 打开相册
function openGallery() {
    console.log('打开相册');
    showToast('相册功能开发中...');
}

// 设置滤镜功能
function setupFilters() {
    const filterOptions = document.querySelectorAll('.filter-option');
    
    filterOptions.forEach(option => {
        option.addEventListener('click', function() {
            // 移除所有活动状态
            filterOptions.forEach(opt => opt.classList.remove('active'));
            
            // 设置当前选项为活动状态
            this.classList.add('active');
            
            // 应用滤镜
            const filter = this.dataset.filter;
            applyFilter(filter);
            
            // 关闭模态框
            setTimeout(() => {
                closeFilterModal();
            }, 300);
        });
    });
    
    // 关闭滤镜模态框
    const closeFilterBtn = document.getElementById('closeFilter');
    closeFilterBtn.addEventListener('click', closeFilterModal);
}

// 打开滤镜模态框
function openFilterModal() {
    const modal = document.getElementById('filterModal');
    modal.classList.remove('hidden');
}

// 关闭滤镜模态框
function closeFilterModal() {
    const modal = document.getElementById('filterModal');
    modal.classList.add('hidden');
}

// 应用滤镜
function applyFilter(filter) {
    const cameraPreview = document.querySelector('.camera-preview');
    
    switch(filter) {
        case 'none':
            cameraPreview.style.filter = 'none';
            break;
        case 'vintage':
            cameraPreview.style.filter = 'sepia(0.8) contrast(1.2) brightness(0.9)';
            break;
        case 'warm':
            cameraPreview.style.filter = 'hue-rotate(20deg) saturate(1.3) brightness(1.1)';
            break;
        case 'cool':
            cameraPreview.style.filter = 'hue-rotate(-20deg) saturate(0.8) brightness(0.9)';
            break;
        case 'vivid':
            cameraPreview.style.filter = 'saturate(1.8) contrast(1.2) brightness(1.1)';
            break;
        case 'mono':
            cameraPreview.style.filter = 'grayscale(1) contrast(1.3)';
            break;
    }
    
    showToast(`已应用${getFilterName(filter)}滤镜`);
}

// 获取滤镜名称
function getFilterName(filter) {
    const filterNames = {
        'none': '原图',
        'vintage': '复古',
        'warm': '暖色',
        'cool': '冷色',
        'vivid': '鲜艳',
        'mono': '黑白'
    };
    return filterNames[filter] || '未知';
}

// 设置位置服务
function setupLocationService() {
    // 模拟位置服务
    updateLocation();
    
    // 定期更新位置
    setInterval(updateLocation, 30000); // 每30秒更新一次
}

// 更新位置信息
function updateLocation() {
    const locationElement = document.querySelector('.fa-map-marker-alt').parentElement;
    const locationText = locationElement.querySelector('span');
    
    // 模拟位置变化
    const locations = ['江心寺', '东塔', '西塔', '江心屿码头', '江心公园'];
    const randomLocation = locations[Math.floor(Math.random() * locations.length)];
    
    if (locationText) {
        locationText.textContent = randomLocation;
    }
    
    // 添加位置获取动画
    const locationIcon = document.querySelector('.fa-map-marker-alt');
    if (locationIcon) {
        locationIcon.style.animation = 'pulse 1s infinite';
        setTimeout(() => {
            locationIcon.style.animation = '';
        }, 3000);
    }
    
    console.log(`当前位置: ${randomLocation}`);
}

// 底部导航
function setupBottomNavigation() {
    const navItems = document.querySelectorAll('.fixed.bottom-0 .text-center');
    
    navItems.forEach((item, index) => {
        item.addEventListener('click', function() {
            // 移除所有活动状态
            navItems.forEach(nav => {
                const icon = nav.querySelector('i');
                const text = nav.querySelector('p');
                icon.classList.remove('text-green-600');
                icon.classList.add('text-gray-400');
                text.classList.remove('text-green-600');
                text.classList.add('text-gray-400');
            });
            
            // 设置当前项为活动状态
            const currentIcon = this.querySelector('i');
            const currentText = this.querySelector('p');
            currentIcon.classList.remove('text-gray-400');
            currentIcon.classList.add('text-green-600');
            currentText.classList.remove('text-gray-400');
            currentText.classList.add('text-green-600');
            
            // 导航逻辑
            const pageNames = ['home', 'map', 'checkin', 'shop', 'profile'];
            const targetPage = pageNames[index];
            
            if (targetPage !== 'checkin') {
                console.log(`导航到 ${targetPage}.html`);
            }
        });
    });
}

// 显示提示
function showToast(message) {
    const toast = document.createElement('div');
    toast.textContent = message;
    toast.style.position = 'fixed';
    toast.style.top = '100px';
    toast.style.left = '50%';
    toast.style.transform = 'translateX(-50%)';
    toast.style.background = 'rgba(0,0,0,0.8)';
    toast.style.color = 'white';
    toast.style.padding = '12px 24px';
    toast.style.borderRadius = '24px';
    toast.style.fontSize = '14px';
    toast.style.zIndex = '1000';
    toast.style.animation = 'fadeInOut 2s ease-out forwards';
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 2000);
}

// 显示成功提示
function showSuccessToast(message) {
    const toast = document.createElement('div');
    toast.innerHTML = `<i class="fas fa-check-circle mr-2"></i>${message}`;
    toast.className = 'success-toast';
    toast.style.position = 'fixed';
    toast.style.top = '50%';
    toast.style.left = '50%';
    toast.style.transform = 'translate(-50%, -50%)';
    toast.style.background = 'rgba(34, 197, 94, 0.9)';
    toast.style.color = 'white';
    toast.style.padding = '16px 24px';
    toast.style.borderRadius = '12px';
    toast.style.fontWeight = '500';
    toast.style.zIndex = '1000';
    toast.style.animation = 'successFade 2s ease-out forwards';
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 2000);
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes flash {
        0% { opacity: 0; }
        50% { opacity: 1; }
        100% { opacity: 0; }
    }
    
    @keyframes shutter {
        0% { opacity: 0; }
        50% { opacity: 1; }
        100% { opacity: 0; }
    }
    
    @keyframes fadeInOut {
        0% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
        20% { opacity: 1; transform: translateX(-50%) translateY(0); }
        80% { opacity: 1; transform: translateX(-50%) translateY(0); }
        100% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
    }
    
    @keyframes successFade {
        0% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.8);
        }
        20% {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }
        80% {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }
        100% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.8);
        }
    }
`;
document.head.appendChild(style);